﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using SmsVotes.DataAccess;
using SmsVotes.Core.Utils;
using SmsVotes.DataAccess.Properties;

namespace SmsVotes.SmsVoting
{
    public partial class Vote : CommandControl
    {

        /// <summary>
        /// Текущее голосование
        /// </summary>
        private DataAccess.Vote CurrentVote
        {
            get
            {
                int id = (int)ViewState["CurrentVoteID"];
                if (id > 0)
                    return VoteManager.GetByID(id);
                else
                    return ViewState["CurrentVote"] as DataAccess.Vote;

            }
            set
            {
                ViewState["CurrentVoteID"] = value.ID;
                if (value.ID == 0)
                    ViewState["CurrentVote"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlSMSNumber.Items.Add(Settings.Default.DedicatedNumber);

                if (Command == COMMAND_VOTECREATE)
                {
                    CurrentVote = new DataAccess.Vote();
                    pQuestions.Visible = false;
                    lbtnSaveTemplate.Text = "Сохранить и перейти к добавлению вопросов";
                }
                else if (Command == COMMAND_VOTEEDIT)
                {
                    int voteID;
                    if (int.TryParse(Request.QueryString["vid"], out voteID))
                    {
                        DataAccess.Vote vote = VoteManager.GetByID(voteID);
                        if (vote != null)
                        {
                            CurrentVote = vote;

                            tbTemplate.Text = vote.Name;
                            tbVotesNumber.Text = vote.MaxVotes.ToString();

                            BindQuestions();
                        }
                    }
                }
            }
        }

        protected void lbtnCreateTemplate_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                // сохраняем голосование
                if (Command == COMMAND_VOTECREATE)
                {
                    SetVoteProps(CurrentVote);
                    try
                    {
                        VoteManager.AddVote(CurrentVote);
                    }
                    catch (Exception ex)
                    {
                        Log.WriteException(ex);
                        return;
                    }
                    Response.Redirect(string.Format("smsvoting.aspx?cmd={0}&vid={1}", COMMAND_QUESTIONCREATE, CurrentVote.ID), true);
                }
                else if (Command == COMMAND_VOTEEDIT)
                {
                    SetVoteProps(CurrentVote);
                    SetQuestionsPriority(CurrentVote);

                    try
                    {
                        VoteManager.Save();
                    }
                    catch (Exception ex)
                    {
                        Log.WriteException(ex);
                        return;
                    }

                    Response.Redirect("smsvoting.aspx", true);
                }
            }
        }
        /// <summary>
        /// Устанавливает приоритет следования вопросам
        /// </summary>
        /// <param name="vote">Текущее голосование</param>
        private void SetQuestionsPriority(SmsVotes.DataAccess.Vote vote)
        {
            if (!string.IsNullOrEmpty(hfQuestions.Value))
            {
                var questionsOrder = hfQuestions.Value.Replace("question[]=", "").Split('&');
                if (questionsOrder != null && questionsOrder.Length > 0)
                {
                    for (int i = 0; i < questionsOrder.Length; i++)
                    {
                        (from q in vote.Questions where q.ID == int.Parse(questionsOrder[i]) select q).First().Priority = i;
                    }
                }
            }
        }

        protected void lbtnCancel_Click(object sender, EventArgs e)
        {
            // Сбрасываем контекст
            VoteManager.Reset();
            Response.Redirect("smsvoting.aspx", true);
        }


        /// <summary>
        /// Устанавливает свойства голосования значениями из UI
        /// </summary>
        /// <param name="vote">Голосование</param>
        private void SetVoteProps(DataAccess.Vote vote)
        {
            vote.Name = tbTemplate.Text;
            vote.Phone = ddlSMSNumber.SelectedItem.Text;
            vote.MaxVotes = int.Parse(tbVotesNumber.Text);
            vote.OwnerLogin = Page.User.Identity.Name;
        }

        protected void lvQuestions_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == COMMAND_QUESTIONDELETE)
            {
                var question = QuestionManager.GetByID(Convert.ToInt32(e.CommandArgument));
                question.VoteReference.SmartLoad();
                question.Vote.VoteState.SmartLoad(question);

                if (question.Vote.VoteState.Count == 0)
                    QuestionManager.Delete(question);
                else
                {
                    // TODO: Кинуть exception
                    ;
                }

                BindQuestions();
            }
        }

        /// <summary>
        /// Связывает грид вопросов с данными отсортированными по приоритету
        /// </summary>
        private void BindQuestions()
        {
            CurrentVote.Questions.SmartLoad(CurrentVote);
            lvQuestions.DataSource = CurrentVote.Questions.OrderBy(q => q.Priority);
            lvQuestions.DataBind();
        }
    }
}